package com.taotao.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;




import com.github.abel533.entity.Example;
import com.github.abel533.mapper.Mapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.pojo.BasePojo;

public abstract class BaseService<T extends BasePojo> {
	
	@Autowired
	private Mapper<T> mapper;
	
	public Mapper<T> getMapper(){
		return this.mapper;
	}
	
		 
	public T queryById(Long id){
		return   this.mapper.selectByPrimaryKey(id);
	}
	
	public T queryOne(T t){
		return this.mapper.selectOne(t);
	}
	
	public List<T> queryAll(){
		
		return this.mapper.select(null);
		
	}
	
	public List<T> queryByWhere(T t){
		return this.mapper.select(t);
	}
	
	public PageInfo<T> queryPageInfoBywhere(T t, Integer page, Integer rows){
		PageHelper.startPage(page, rows);
		List<T> list = this.mapper.select(t);
		return new PageInfo<T>(list);
	}
	
	public PageInfo<T> queryPageInfoByExample(Example example, Integer page, Integer rows){
		PageHelper.startPage(page, rows);
		List<T> list = this.mapper.selectByExample(example);
		return new PageInfo<T>(list);
	}
	
	public int save(T t){
		t.setCreated(new Date());
		t.setUpdated(new Date());
		int status = this.mapper.insert(t);
		return status;
	}
	
	public int saveSelective(T t){
		t.setCreated(new Date());
		t.setUpdated(new Date());
		int i = this.mapper.insertSelective(t);
		return i;
	}
	//根据主键进行更新,这里最多只会更新一条数据
	//参数为实体类
	public Integer update(T t){
		return this.mapper.updateByPrimaryKey(t);
	}
	//根据主键进行更新
	//只会更新不是null的数据
	public Integer updateSelective(T t){
		return this.mapper.updateByPrimaryKeySelective(t);
	}
	//通过主键进行删除,这里最多只会删除一条数据
	//单个字段做主键时,可以直接写主键的值
	//联合主键时,key可以是实体类,也可以是Map
	public Integer deleteByPrimaryKey(Long key){
		return this.mapper.deleteByPrimaryKey(key);
	}
	//根据实体类中字段不为null的条件进行删除,条件全部使用=号and条件
	public Integer delete(T t){
		return this.mapper.delete(t);
	}
	
	public Integer deleteByIds(Class<T> clazz,String property,List<Object> ids){
		Example example = new Example(clazz);
		example.createCriteria().andIn(property, ids);
		return this.mapper.deleteByExample(example);
	}
}
